package de.slothsoft.wasbinich.swingclient.database;

import java.util.Map;
import java.util.Map.Entry;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;

import de.slothsoft.wasbinich.core.database.DatabaseException;
import de.slothsoft.wasbinich.core.database.webservice.RestCommunicator;
import de.slothsoft.wasbinich.core.database.webservice.WebserviceUtil;

public class JerseyRestCommunicator implements RestCommunicator {

    private static final String CLIENT_CREDENTIALS = "V2FzIEJpbiBJY2ggQ2xpZW50OjlDOEVGMTE4LTA0RTktNEEwRS1COEJFLUFGQzQ5MTdDQ0NGOQ==";

    private final boolean oauthResponse;

    public JerseyRestCommunicator(boolean oauthResponse) {
	this.oauthResponse = oauthResponse;
    }

    @Override
    public String get(String url) throws DatabaseException {
	WebResource.Builder webResource = createResource(url);
	return parseResponse(webResource.get(ClientResponse.class));
    }

    @Override
    public String post(String url, Map<String, String> parameters) throws DatabaseException {
	WebResource.Builder webResource = createResource(url);
	MultivaluedMap<String, String> formData = new MultivaluedMapImpl();
	for (Entry<String, String> entry : parameters.entrySet()) {
	    formData.add(entry.getKey(), entry.getValue());
	}
	return parseResponse(webResource.post(ClientResponse.class, formData));
    }

    private WebResource.Builder createResource(String url) {
	Client client = Client.create();
	WebResource webResource = client.resource(url);
	return webResource.header("Authorization", "Basic " + CLIENT_CREDENTIALS).accept(MediaType.APPLICATION_JSON);
    }

    protected String parseResponse(ClientResponse response) throws DatabaseException {
	if (response.getStatus() != 200) {
	    String errorJson = response.getEntity(String.class);
	    System.err.println("Failing because of: " + errorJson);
	    if (this.oauthResponse)
		throw WebserviceUtil.createOAuth2Exception(errorJson);
	    throw WebserviceUtil.createDatabaseException(errorJson);
	}
	return response.getEntity(String.class);
    }
}
